package javatunes;
import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.TreeSet;

public class javatunes {
	TreeSet<String> artists;
	TreeSet<String> albums;
	TreeSet<String> titles;
	TreeSet<String> genres;
	String[] artists_arr;
	String[] albums_arr;
	String[] titles_arr;
	String[] genres_arr;
	
	ArrayList<mhit> tracks;
	
	private static javatunes jt;
	public static itunesdbreader itunesdb;
	
	public javatunes (ArrayList<mhit> alltracks) {
		tracks=alltracks;
		setuparraylists(tracks);
	}
	
	static JList artistjlist;
	static JList albumjlist;
	static JList titlejlist;
	static JList genrejlist;
	private static void createAndShowGUI() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		
		JFrame.setDefaultLookAndFeelDecorated(true);
		final JFrame frame=new JFrame("javatunes");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLayout(new GridLayout(0,1));
		
		JPanel mainpanel=new JPanel();
		mainpanel.setLayout(new BoxLayout(mainpanel,BoxLayout.Y_AXIS));
		
		JPanel browsepanel=new JPanel();
		browsepanel.setLayout(new BoxLayout(browsepanel,BoxLayout.X_AXIS));
		
		genrejlist=new JList(jt.genres.toArray());
		artistjlist=new JList(jt.artists.toArray());
		albumjlist=new JList(jt.albums.toArray());
		titlejlist=new JList(jt.titles.toArray());
		
		genrejlist.setVisibleRowCount(8);
		artistjlist.setVisibleRowCount(8);
		albumjlist.setVisibleRowCount(8);
		
		genrejlist.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				genrejlistChanged(e);
			}
		});
		artistjlist.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				artistjlistChanged(e);
			}
		});
		albumjlist.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
				albumjlistChanged(e);
			}
		});
		
		JScrollPane genrescroll=new JScrollPane(genrejlist);
		JScrollPane artistscroll=new JScrollPane(artistjlist);
		JScrollPane albumscroll=new JScrollPane(albumjlist);
		JScrollPane titlescroll=new JScrollPane(titlejlist);
		
		browsepanel.add(genrescroll);
		browsepanel.add(artistscroll);
		browsepanel.add(albumscroll);
		
		mainpanel.add(browsepanel);
		mainpanel.add(titlescroll);
		
		JButton export=new JButton("Export playlist...");
		export.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				exportbuttonclicked(frame);
			}
		});
		mainpanel.add(export);
		
		frame.add(mainpanel);
		frame.pack();
		frame.setVisible(true);
	}
	
	static void exportbuttonclicked (JFrame frame) {
		JFileChooser fc=new JFileChooser();
		int returnval=fc.showSaveDialog(frame);
		if (returnval==JFileChooser.APPROVE_OPTION) {
			File file=fc.getSelectedFile();
			try {
		        FileOutputStream fout = new FileOutputStream(file);
		        PrintStream out=new PrintStream(fout);
		        out.println("[playlist]");
		        for (int i=0;i<jt.tracks.size();i++) {
					out.println("File"+(i+1)+"="+jt.tracks.get(i).getFileName(itunesdbreader.IPODDRIVE));	
				}
		        out.close();
		        fout.close();
		    } catch (IOException e) {
		    	e.printStackTrace();
		    }
		    System.out.println("");
			
		}
	}
	
	static void genrejlistChanged(ListSelectionEvent e){
		//if (e.getValueIsAdjusting()) return;
		Object[] genres=genrejlist.getSelectedValues();
		jt.tracks=itunesdbreader.search(itunesdb.alltracks,null,null,null,genres);
		jt.setuparraylists(jt.tracks);
		updateartistlist();
		updatealbumlist();
		updatetitlelist();
	}
	
	static void artistjlistChanged(ListSelectionEvent e){
		//if (e.getValueIsAdjusting()) return;
		Object[] genres=genrejlist.getSelectedValues();
		Object[] artists=artistjlist.getSelectedValues();
		jt.tracks=itunesdbreader.search(itunesdb.alltracks,artists,null,null,genres);
		jt.setuparraylists(jt.tracks);
		updatealbumlist();
		updatetitlelist();
	}
	
	static void albumjlistChanged(ListSelectionEvent e){
		//if (e.getValueIsAdjusting()) return;
		Object[] genres=genrejlist.getSelectedValues();
		Object[] artists=artistjlist.getSelectedValues();
		Object[] albums=albumjlist.getSelectedValues();
		jt.tracks=itunesdbreader.search(itunesdb.alltracks,artists,albums,null,genres);
		jt.setuparraylists(jt.tracks);
		updatetitlelist();
	}
	
	static void updateartistlist() {
		DefaultListModel model=new DefaultListModel();
		for (int i=0;i<jt.artists_arr.length;i++) {
			model.addElement(jt.artists_arr[i]);
		}
		artistjlist.setModel(model);
	}
	
	static void updatealbumlist() {
		DefaultListModel model=new DefaultListModel();
		for (int i=0;i<jt.albums_arr.length;i++) {
			model.addElement(jt.albums_arr[i]);
		}
		albumjlist.setModel(model);
		
	}
	
	static void updatetitlelist() {
		DefaultListModel model=new DefaultListModel();
		for (int i=0;i<jt.titles_arr.length;i++) {
			model.addElement(jt.titles_arr[i]);
		}
		titlejlist.setModel(model);
	}
		
	public void setuparraylists(ArrayList<mhit> tracks) {
		long starttime=System.currentTimeMillis();
		artists=new TreeSet<String>();
		albums=new TreeSet<String>();
		titles=new TreeSet<String>();
		genres=new TreeSet<String>();
		
		genres.add("(All)");
		artists.add("(All)");
		albums.add("(All)");
		titles.add("(All)");
		
		
		mhit current;
		for (int i=0; i<tracks.size(); i++) {
			current=tracks.get(i);
			if (current.artist.length()>0) artists.add(current.artist);
			if (current.album.length()>0) albums.add(current.album);
			if (current.title.length()>0) titles.add(current.title);
			if (current.genre.length()>0) genres.add(current.genre);
		}

		artists_arr=artists.toArray(new String[0]);
		albums_arr=albums.toArray(new String[0]);
		titles_arr=titles.toArray(new String[0]);
		genres_arr=genres.toArray(new String[0]);
		System.out.println("setuparraylists took: "+(System.currentTimeMillis()-starttime));
	}
	
	public static void main (String [] args) throws Exception {
		itunesdb=new itunesdbreader();
		jt=new javatunes(itunesdb.alltracks);
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	createAndShowGUI();
            }
        });
	}
	
}
